<?php
declare (strict_types = 1);

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;
use app\common\model\ClothColor as COLOR_M;

class ClothMain extends Model{
    use SoftDelete;
    protected $deleteTime = "delete_time";
	
	/**
	 * 分类一对一关联
	 */
	public function typeName(){
	    return $this->hasOne(ClothType::class, 'id', 'tid')->bind(['type'=>'name']);
	}
	
	/**
	 * 颜色一对一关联
	 */
	public function color(){
	    return $this->hasOne(ColorLib::class, 'id', 'pid');
	}
		
	// 获取列表
    public static function getList($where = [],$order=[],$field='*'){
        $limit = I('get.limit/d');
		$tid = I('tid',0);
        
		//按品名查找
		if ($title = I("title")) {
		   $where[] = ["title", "like", "%" . $title . "%"];
		}
		//按产品标题查找
		if ($subject = I("subject")) {
		   $where[] = ["subject", "like", "%" . $subject . "%"];
		}
		//按编号查找
		if ($number = I("number")) {
		   $where[] = ["number", "like", "%" . $number . "%"];
		}
		//按供应编号查找
		if ($onumber = I("onumber")) {
		   $where[] = ["onumber", "like", "%" . $onumber . "%"];
		}
		//按关键字
		if ($keyword = I("keyword")) {
		   $where[] = ["number|title", "like", "%" . $keyword . "%"];
		}
		if($order=="" || $order==[]){
            $order=['status'=>'desc','sort'=>'asc'];
        }
		if($tid>0){
			$where[] = ['tid','=',$tid];
		}
        $list = self::field($field)->order($order)->with(['typeName'])->where($where)->paginate($limit);
        return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
    }
	
	// 获取列表数据
	public static function listData($where=[],$order="",$file="*",$n_page=0,$limit=20){
		$data=self::order($order)->where($where)->with(['typeName']);
		if($n_page>0){
			$data=$data->page($n_page,$limit);
		}
		$data=$data->select()->toArray();
		
		return $data;
	}
	
	// 获取差价表信息
	public static function costList($where=[]){
	    $limit = I('get.limit/d');

	    $list = self::order(['number'=>'asc','sort'=>'asc'])->with(['typeName'])->where($where)->paginate($limit);
		foreach($list as &$v){
			$v['n_price1']=price_one($v['price1']);
			$v['l_profit1']=cloth_diff($v,false);
			$v['l_profit2']=cloth_diff2($v,false);
			//虚假差价
			$v['f_profit1']=round(cloth_diff($v,false)/10+1,2);
			$v['f_profit2']=round(cloth_diff2($v,false)/10+1,2);
		}		
	    return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
	}
	
	// 获取报价表信息
	public static function tableList($where=[]){
		$limit = I('get.limit/d');
		
		$list=self::alias('m')
		->leftJoin('cloth_type t','m.tid=t.id')
		->field('m.*,t.name as type')
		->order(['t.sort'=>'asc','m.sort'=>'asc'])
		->where($where)
		->paginate($limit);

	    return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
	}
	
	// 获取某个单条记录
	public static function info($id,$more=false){
		$kg=25;
		if(!is_array($id)){
			$T=self::find($id);
		}else{
			$T=self::where($id)->find();
		}
		
		if($more && $T!=''){
			$T['ykg']=round(1000/$T['kgy']/1000,1);								//1码多少千克
			$T['yg']=round(1000/$T['kgy']);										//1码多少克
			$T['yb']=$T['ykg']*2.2;												//1码多少磅
			$T['mkg']=round(1000/$T['kgm']/1000,1);								//1米多少千克
			$T['mg']=round(1000/$T['kgm']);										//1米多少克
			$T['mb']=$T['mkg']*2.2;												//1米多少磅
			$T['ek']=$T['tube']+$T['emptykg'];									//纸筒空差总和
			$T['pure_price1']=round($T['price1']*$kg/($kg-$T['ek']),1);			//净布价格
			$T['pure_price2']=round($T['price2']*$kg/($kg-$T['ek']),1);			//白色净布价
			$T['pure_tax_price1']=self::r_integer($T['price1']/0.99);			//杂色含税价（小规模）
			$T['pure_tax_price2']=self::r_integer($T['price1']/0.94);			//杂色含税价（加工票）
			$T['pure_tax_price3']=self::r_integer($T['price1']/0.92);			//杂色含税价（布票）
			$T['pure_tax_price4']=self::r_integer($T['pure_price1']/0.99);		//杂色净布含税价（小规模）
			$T['pure_tax_price5']=self::r_integer($T['pure_price1']/0.94);		//杂色净布含税价（加工票）
			$T['pure_tax_price6']=self::r_integer($T['pure_price1']/0.92);		//杂色净布含税价（布票）
			$T['vir_price1']=round($T['space1']*($kg-$T['ek'])/$kg,1);			//拿货杂色毛重价
			$T['vir_price2']=round($T['space2']*($kg-$T['ek'])/$kg,1);			//拿货白色毛重价
			$T['piecey']=intval(($kg-$T['ek'])*$T['kgy']);						//每匹码数
			$T['piecem']=intval(($kg-$T['ek'])*$T['kgm']);						//每匹米数
			$T['wholesaley']=round(($kg*$T['price1'])/$T['piecey'],1);			//大货码价
			$T['wholesalem']=round(($kg*$T['price1'])/$T['piecem'],1);			//大货米价
			$T['by_price1']=$T['price1']+1.5;						            //大货包邮价
			$T['by_price4']=$T['price4']+5;										//版布包邮价
		}
		return $T;
	}
	
	//净布价取整
	private static function r_integer($val){
		$val=sprintf("%.2f", $val);
		$min_int=explode('.',$val);
		if($min_int[1]<5){
			$val=$min_int[0]+0.5;
		}else{
			$val=$min_int[0]+1;
		}
		return $val;
	}
	
	//	生成订单打印数据
	//	订单数据，订单明细数据，报表文件名称，
	public static function printData($T,$print=[],$name='FabricLabel1'){
		$data=[
		    "method" =>"printreport",
		    "ReportType" =>"gridreport",
		    "ReportName" => $name.'.grf',
		    "ReportVersion" =>"1",
		    "ReportUrl" => get_host()."/static/tool/print/".$name.".grf",
			"PrinterName" => $print['printer_name2'],
		    "Preview" => 1,//$print['preview'],
		    "token" => md5(time().''),
		    "taskid" => time(),
			"Control" => [],
			"Field" => [],
			"Parameter"=>[],
			"Data" => $T,
		];

		$field=array_keys($T[0]);
		
		//循环替换内容
		foreach($field as $f){
			$data['Field'][]=[
				'type' =>'ftString',
				'name' => $f,
				'size' => 255,
				'required' =>false
			];
		};
		return $data;
	}
	
	//剪版价取整
	private static function r_integer2($val){
		return ceil($val);
	}
	
	//写入后
	public static function onAfterWrite($model){
		F($model->uuid.'/minApp/colth_class',null);	//清除缓存
		F($model->uuid.'/colth_list',null);			//清除缓存
	}
	
	//删除前
	public static function onBeforeDelete($model){
		if($model->delete_time!=null){				//真实删除
			COLOR_M::where(['pid'=>$model->id])->delete();
		}
	}
	
	//删除后
	public static function onAfterDelete($model){
		F($model->uuid.'/minApp/colth_class',null);	//清除缓存
		F($model->uuid.'/colth_list',null);			//清除缓存		
	}
		
	/** 获取器 **/
	public function getCoverAttr($value){
		if(is_string($value)){
			$value=unserialize($value);
		}else if($value==false || $value==""){
			$value=[];
		}
	    return $value;
	}
	
	public function getPurposeAttr($value){
		$value=explode(',',$value);
	    return $value;
	}
	
	public function getSeasonAttr($value){
		$value=explode(',',$value);
	    return $value;
	}
	
	/** 预处理数据 **/
	
}
